package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.Listener.SubjectExcelListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.vo.subject.OneSubject;
import com.atguigu.eduservice.entity.vo.subject.TwoSubject;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author Cyrus
 * @since 2020-12-07
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    /**
     * 添加课程分类
     */
    @Override
    public void saveSubject(MultipartFile file,EduSubjectService subjectService) {
        try{
            //文件输入流
            InputStream in = file.getInputStream();
            EasyExcel.read(in, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //查询所有一级分类 eq:等于
        List<EduSubject> OneSubjects = baseMapper.selectList(new QueryWrapper<EduSubject>().lambda().eq(EduSubject::getParentId, "0"));
        ArrayList<OneSubject> arrayListOne = new ArrayList<>();
        for (EduSubject eduSubject : OneSubjects) {
            ArrayList<TwoSubject> arrayListTwo = new ArrayList<>();
            //查询出当前一级分类的所有二级分类
            List<EduSubject> TwoSubjectIsOneSubject = baseMapper.selectList(new QueryWrapper<EduSubject>().lambda().eq(EduSubject::getParentId, eduSubject.getId()));
            //将所有二级分类封装到TwoSubject中
            for (EduSubject subject : TwoSubjectIsOneSubject) {
                TwoSubject twoSubject = new TwoSubject();
                BeanUtils.copyProperties(subject,twoSubject);
                arrayListTwo.add(twoSubject);
            }
            //将所有TwoSubject封装到一级分类中
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduSubject,oneSubject);
            oneSubject.setChildren(arrayListTwo);
            arrayListOne.add(oneSubject);
        }
        return arrayListOne;
    }
}
